<?php 
class Zen_Cache_Factory {
	
	private static $_manager = null;
	
	const TEMPLATE_NAME = 'zen_template';
	
	private static function _getCommonCacheDir() {
		$cnf=Zend_Registry::get('cnf');
		return $cnf->cache_dir;
	}
	
	private static function _getManager() {
		$manager = self::$_manager;
		if (! $manager ) 
			$manager = new Zend_Cache_Manager();
		return $manager; 
	}
	
	private static function _setManager($manager) {
		self::$_manager = $manager;
	}
	
	public static function initTemplate() {
		$template = array(
		    'frontend' => array(
			    'name' => 'Core',
		        'options' => array(
	            	'lifetime' => NULL,
	            	'automatic_serialization' => true
				)
			),
	    	'backend' => array(
	        	'name' => 'File',
	        	'options' => array(
					'cache_file_umask'=> 0777,
					'hashed_directory_level' => 2,
					'hashed_directory_umask' => 0777,
					'cache_dir' => self::_getCommonCacheDir(),
					'file_name_prefix' => 'zen',
	            )
	        )
       	);
       	$manager = self::_getManager();
       	$manager->setCacheTemplate(self::TEMPLATE_NAME, $template);
       	self::_setManager($manager);
	}
	
	public static function get($resource) {
		$cache_name = $resource . '_chace';
		$manager = self::_getManager();
		$cache = $manager->getCache(self::TEMPLATE_NAME);
		$cache_dir = self::_getCommonCacheDir() . $resource . '/';
		$cache->getBackend()->setOption('cache_dir', $cache_dir);
		$cache->getBackend()->setOption('file_name_prefix', $resource);
		if (! Zend_Registry::isRegistered($cache_name) ) {	
			if (! file_exists ( $cache_dir)) {
				mkdir ( $cache_dir, 0777, true );
			}
			Zend_Registry::set($cache_name,$cache_name);
		}
		return $cache;
	}
	
}